package com.pro01.backend.controller;

import com.pro01.backend.pojo.ForumPost;
import com.pro01.backend.pojo.PageResult;
import com.pro01.backend.pojo.Result;
import com.pro01.backend.service.ForumPostLikeService;
import com.pro01.backend.service.ForumPostService;
import com.pro01.backend.utils.JwtUtil;
import com.pro01.backend.utils.TokenUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 用户查看论坛接口 + 发帖
 */
@RestController
@RequestMapping("/forums")
public class ForumPostController {

    @Autowired
    private ForumPostService forumPostService;


    /**
     * 用户发帖
     */
    @PostMapping("/{forumId}/posts")
    public Result<Void> createPost(@PathVariable Long forumId,
                                   @RequestBody ForumPost post,
                                   HttpServletRequest request) {

        // Token 校验
//        String token = request.getHeader("Authorization");
//        Map<String, Object> claims = JwtUtil.parseToken(token);
//        if (claims == null) {
//            return Result.error("无效的 Token，请重新登录");
//        }

        try {
            //Long userId = ((Number) claims.get("userId")).longValue();
            Long userId = TokenUtil.getUserId(request);

            post.setForumId(forumId);
            post.setUserId(userId);

            forumPostService.createPost(post);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("发帖失败：" + e.getMessage());
        }
    }

    /**
     * 分页查询某个板块下的帖子
     */
    @GetMapping("/{forumId}/posts")
    public Result<PageResult<ForumPost>> getPostsByForum(
            @PathVariable Long forumId,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            HttpServletRequest request) {

        try {
            Long userId = TokenUtil.getUserId(request);
            PageResult<ForumPost> pageResult = forumPostService.getPostsByForum(forumId, userId, pageNum, pageSize);
            return Result.success(pageResult);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取帖子失败：" + e.getMessage());
        }
    }



}

